using Microsoft.AspNetCore.Mvc;
using UniversalAdminSystem.Application.PermissionManagement.DTOs;
using UniversalAdminSystem.Application.PermissionManagement.Interfaces;
using UniversalAdminSystem.Infrastructure.Services;
using UniversalAdminSystem.Api.Attributes;
using UniversalAdminSystem.Application.Common.Results;

namespace UniversalAdminSystem.Api.Controllers;

/// <summary>
/// 权限管理控制器
/// </summary>
[ApiController]
[Route("api/permissions")]
public class PermissionController : ControllerBase
{
    private readonly IPermissionManagementAppService _permissionAppService;
    private readonly PermissionRuleConfigService _permissionRuleConfigService;

    public PermissionController(IPermissionManagementAppService permissionAppService, PermissionRuleConfigService permissionRuleConfigService)
    {
        _permissionAppService = permissionAppService;
        _permissionRuleConfigService = permissionRuleConfigService;
    }

    /// <summary>
    /// 获取所有权限列表
    /// </summary>
    [HttpGet]
    [RequirePermission("permission:Read")]
    public async Task<IActionResult> GetAllPermissionsAsync()
    {
        try
        {
            var permissions = await _permissionAppService.GetAllPermissionAsync();
            return Ok(Result<IEnumerable<PermissionDto>>.Success(permissions));
        }
        catch (Exception ex)
        {
            return BadRequest(Result<IEnumerable<PermissionDto>>.Failure(ex.Message));
        }
    }

    /// <summary>
    /// 创建新权限
    /// </summary>
    [HttpPost("create")]
    [RequirePermission("permission:Create")]
    public async Task<IActionResult> CreatePermissionAsync([FromBody] PermissionCreateDto createDto)
    {
        try
        {
            var permission = await _permissionAppService.CreatePermissionAsync(createDto);
            return Ok(Result<PermissionDto>.Success(permission));
        }
        catch (InvalidOperationException ex)
        {
            // 检查是否是重复权限错误
            if (ex.Message.Contains("已存在"))
            {
                return Conflict(Result<PermissionDto>.Failure(ex.Message));
            }
            return BadRequest(Result<PermissionDto>.Failure(ex.Message));
        }
        catch (Exception ex)
        {
            return BadRequest(Result<PermissionDto>.Failure($"创建权限失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 删除权限
    /// </summary>
    [HttpDelete("{permissionId}")]
    [RequirePermission("permission:Delete")]
    public async Task<IActionResult> DeletePermissionAsync(Guid permissionId)
    {
        try
        {
            await _permissionAppService.RemovePermissionAsync(permissionId);
            return Ok(Result.Success("权限删除成功"));
        }
        catch (Exception ex)
        {
            return BadRequest(Result.Failure(ex.Message));
        }
    }


    // 已废弃（请使用Role Controller的分配api）
    // /// <summary>
    // /// 为角色分配权限
    // /// </summary>
    // [HttpPost("assign")]
    // [RequirePermission("permission:Update")]
    // public async Task<IActionResult> AssignPermissionToRoleAsync([FromBody] AssignPermissionDto assignDto)
    // {
    //     try
    //     {
    //         await _permissionAppService.AssignPermissionToRoleAsync(assignDto);
    //         return Ok(Result.Success("权限分配成功"));
    //     }
    //     catch (Exception ex)
    //     {
    //         return BadRequest(Result.Failure(ex.Message));
    //     }
    // }

    /// <summary>
    /// 获取权限规则配置
    /// </summary>
    [HttpGet("rules")]
    [RequirePermission("permission:Read")]
    public IActionResult GetPermissionRulesAsync()
    {
        try
        {
            var rules = _permissionRuleConfigService.GetCurrentConfig();
            return Ok(Result<Dictionary<UniversalAdminSystem.Domian.PermissionManagement.ValueObjects.PermissionAction, HashSet<string>>>.Success(rules));
        }
        catch (Exception ex)
        {
            return BadRequest(Result<Dictionary<UniversalAdminSystem.Domian.PermissionManagement.ValueObjects.PermissionAction, HashSet<string>>>.Failure(ex.Message));
        }
    }

    /// <summary>
    /// 更新权限规则配置
    /// </summary>
    [HttpPut("rules")]
    [RequirePermission("permission:Update")]
    public IActionResult UpdatePermissionRulesAsync([FromBody] Dictionary<string, List<string>> newRules)
    {
        try
        {
            // TODO: 这里应该校验当前用户是否为超级管理员
            _permissionRuleConfigService.UpdateConfig(newRules);
            return Ok(Result.Success("权限规则更新成功"));
        }
        catch (Exception ex)
        {
            return BadRequest(Result.Failure(ex.Message));
        }
    }

    /// <summary>
    /// 刷新权限规则配置
    /// </summary>
    [HttpPost("rules/refresh")]
    [RequirePermission("permission:Update")]
    public IActionResult RefreshPermissionRulesAsync()
    {
        try
        {
            _permissionRuleConfigService.RefreshConfig();
            return Ok(Result.Success("权限规则刷新成功"));
        }
        catch (Exception ex)
        {
            return BadRequest(Result.Failure(ex.Message));
        }
    }
}